<!-- 条目管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="24">
      <!-- 条目列表 -->
      <el-col :lg="24" :xs="24">
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-form
            ref="queryFormRef"
            :model="queryParams"
            :inline="true"
            label-width="auto"
          >
            <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                placeholder="条目名"
                clearable
              />
            </el-form-item>
            <el-form-item class="search-buttons">
              <el-button type="primary" icon="search" @click="handleQuery">
                搜索
              </el-button>
              <el-button icon="refresh" @click="handleResetQuery">
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="hover" class="data-table">
          <div class="data-table__toolbar" style="margin-bottom: 10px">
            <div class="data-table__toolbar--actions">
              <el-button
                v-hasPerm="['sysLangEdit']"
                type="success"
                icon="plus"
                @click="handleOpenDialog()"
              >
                新增
              </el-button>
              <el-button
                v-hasPerm="'sysLangDelBtn'"
                type="danger"
                icon="delete"
                :disabled="selectIds.length === 0"
                @click="handleDelete()"
              >
                删除
              </el-button>
              <el-button
                v-hasPerm="['sysLangEdit']"
                type="warning"
                icon="refresh"
                @click="handleUpdateLang()"
              >
                更新
              </el-button>
            </div>
          </div>

          <el-table
            v-loading="loading"
            :data="pageData"
            :selectable="selectable"
            border
            stripe
            highlight-current-row
            class="data-table__content"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="条目名称" align="center" prop="title" />
            <el-table-column
              v-for="(item, index) in headData"
              :key="index"
              :label="item.title"
              align="center"
              :prop="'lang_' + item.id"
            />
            <el-table-column label="操作" fixed="right" align="center">
              <template #default="scope">
                <el-button
                  v-hasPerm="'sysLangEdit'"
                  type="primary"
                  icon="edit"
                  link
                  size="small"
                  @click="handleOpenDialog(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-hasPerm="'sysLangDelBtn'"
                  type="danger"
                  icon="delete"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-model:current-page="queryParams.page"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[15, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleQuery"
            @current-change="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000"
      :before-close="handleCloseDialog"
      :align-center="true"
      :close-on-click-modal="false"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="条目名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item
          v-for="(item, index) in formDataHead"
          :key="index"
          :label="item.lang_title"
        >
          <el-input v-model="item.text" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from "@/store/modules/app";
import { DeviceEnum } from "@/enums/DeviceEnum";

import LangItemAPI, {
  LangInfo,
  LangItemUpdate,
  LangItemInfo,
  LangItemListVO,
  LangItemPageQuery,
  LangItemList,
} from "@/api/system/langitem.api";

defineOptions({
  name: "SysLangItem",
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryFormRef = ref();
const dataFormRef = ref();

const queryParams = reactive<LangItemPageQuery>({
  page: 1,
  pageSize: 15,
});
const selectable = (row: LangItemInfo) => ![1].includes(Number(row.id));
const pageData = ref<LangItemList[]>();
const headData = ref<LangInfo[]>([]);
const formDataHead = ref<LangItemUpdate[]>([]);
const total = ref(0);
const loading = ref(false);

const dialog = reactive({
  visible: false,
  title: "新增条目",
});
const drawerSize = computed(() =>
  appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"
);

let formData = reactive<LangItemInfo>({
  id: "",
  title: "",
});

let tempItem = reactive<LangItemUpdate>({
  lang_title: "",
  lang_id: "",
  item_id: "",
  text: "",
});

const rules = reactive({
  title: [{ required: true, message: "条目名称", trigger: "blur" }],
});

// 选中的条目ID
const selectIds = ref<number[]>([]);

// 查询
async function handleQuery() {
  loading.value = true;
  LangItemAPI.getPage(queryParams)
    .then((data: LangItemListVO) => {
      pageData.value = data.list;
      total.value = data.total;
      headData.value = data.head;
      formDataHead.value = [];
      headData.value.forEach((element) => {
        formDataHead.value.push({
          lang_title: element.title,
          lang_id: element.id,
          item_id: "",
          text: "",
        });
      });
    })
    .finally(() => {
      loading.value = false;
    });
}
// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  queryParams.keywords = "";
  handleQuery();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

/**
 * 打开弹窗
 *
 * @param id 条目ID
 */
async function handleOpenDialog(data?: any) {
  dialog.visible = true;
  if (data?.id) {
    dialog.title = "修改条目";
    //复制 data 给formData.value
    formDataHead.value.forEach((element) => {
      element.item_id = data.id;
      element.text = "";
      if (data && element.lang_id) {
        const langKey = "lang_" + element.lang_id;
        element.text = data[langKey] || "";
      }
    });
    // console.log(formDataHead.value);
    Object.assign(formData, data);
  } else {
    formDataHead.value.forEach((element) => {
      element.item_id = "";
      element.text = "";
    });
    dialog.title = "新增条目";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = "";
  formData.title = "";
}

// 提交条目表单（防抖）
const handleSubmit = useDebounceFn(() => {
  dataFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const dataId = formData.id;
      formData.detail = JSON.stringify(formDataHead.value);
      loading.value = true;
      if (dataId) {
        LangItemAPI.update(formData)
          .then(() => {
            ElMessage.success("修改条目成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        LangItemAPI.create(formData)
          .then(() => {
            ElMessage.success("新增条目成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/**
 * 删除条目
 *
 * @param id  条目ID
 */
function handleDelete(id?: number) {
  const dataIds = [id || selectIds.value].join(",");
  if (!dataIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除条目?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      LangItemAPI.deleteByIds({ ids: dataIds })
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

/*
 * 更新语言
 */
function handleUpdateLang() {
  ElMessageBox.confirm("确认更新条目?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      LangItemAPI.update({
        is_update: "file",
        title: "",
      })
        .then(() => {
          ElMessage.success("更新成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消更新");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
